package cn.alone.basic.interceprot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 2.后端登录拦截器
 * @author lanan
 */
@Component  //和service注入一个道理
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*获取请求头中的token*/
        String token = request.getHeader("token");
        /*校验token是否存在*/
        if(!StringUtils.isEmpty(token)){
            /*token存在查询存储在redis中的信息*/
            Object tokenTmp = redisTemplate.opsForValue().get(token);
            /*判断是否过期*/
            if (tokenTmp!=null){
                /*放行,刷新过期时间 30分钟*/
                redisTemplate.opsForValue().set(token, tokenTmp,30, TimeUnit.MINUTES);
                return true;
            }
        }

        /*token不存在,返回错误给前端*/
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        /*拦截请求*/
        return false;
    }
}
